/**
 * 知识库状态管理
 */
import { defineStore } from 'pinia';
import type { Category, Document, PaginatedResult } from '../types';
import { 
  getDocCategories, 
  getDocuments, 
  deleteDocument, 
  generateDocQA,
  createDocCategory,
  updateDocCategory,
  deleteDocCategory
} from '../api/knowledge';
import { message } from 'ant-design-vue';
import { request } from '../utils/request';

export const useKnowledgeStore = defineStore('knowledge', {
  state: () => ({
    // 分类树
    categories: [] as Category[],
    
    // 文档列表
    documents: [] as Document[],
    
    // 当前选中的分类ID
    currentCategory: 'all',
    
    // 加载状态
    loading: false,
    
    // 文档总数
    total: '0',
    
    // 分页
    pageSize: 10,
    pageNumber: 1,
    
    // 搜索关键词
    searchQuery: '',
    
    // 错误信息
    error: '',
  }),
  
  getters: {
    // 获取所有分类
    getCategories: (state) => state.categories,
    
    // 获取当前分类ID
    getCurrentCategoryId: (state) => state.currentCategory,
    
    // 获取文档列表
    getFilteredDocuments: (state) => {
      if (state.currentCategory === 'all') {
        return state.documents;
      }
      
      return state.documents.filter(doc => doc.category === state.currentCategory);
    },
    
    // 获取总文档数
    getTotalCount: (state) => parseInt(state.total) || 0,
    
    // 是否在加载中
    isLoading: (state) => state.loading,
    
    getDocumentById: (state) => (id: string) => state.documents.find(doc => doc.docBizId === id),
  },
  
  actions: {
    /**
     * 设置加载状态
     * @param status 加载状态
     */
    setLoading(status: boolean) {
      this.loading = status;
    },
    
    /**
     * 设置错误信息
     * @param errorMsg 错误消息
     */
    setError(errorMsg: string) {
      this.error = errorMsg;
    },
    
    /**
     * 设置当前选中的分类
     * @param categoryId 分类ID
     */
    setCurrentCategory(categoryId: string) {
      this.currentCategory = categoryId;
      this.loadDocuments(1); // 重置为第一页
    },
    
    /**
     * 设置搜索关键词
     * @param query 搜索关键词
     */
    setSearchQuery(query: string) {
      this.searchQuery = query;
    },
    
    /**
     * 加载分类树
     */
    async loadCategories() {
      try {
        this.setLoading(true);
        const categories = await getDocCategories();
        this.categories = categories;
        this.setError('');
      } catch (error) {
        this.setError('加载分类失败');
        console.error('加载分类失败:', error);
      } finally {
        this.setLoading(false);
      }
    },
    
    /**
     * 加载文档列表
     * @param pageNumber 页码
     * @param pageSize 每页数量
     * @param query 搜索关键词
     * @param categoryId 分类ID
     */
    async loadDocuments(
      pageNumber?: number, 
      pageSize?: number, 
      query?: string, 
      categoryId?: string
    ) {
      try {
        this.setLoading(true);
        
        const pn = pageNumber || this.pageNumber;
        const ps = pageSize || this.pageSize;
        const q = query !== undefined ? query : this.searchQuery;
        const cid = categoryId || this.currentCategory;
        
        const result = await getDocuments(pn, ps, q, cid);
        
        this.documents = result.list;
        this.total = result.total;
        this.pageNumber = pn;
        this.pageSize = ps;
        this.searchQuery = q;
        this.currentCategory = cid;
        this.setError('');
      } catch (error) {
        this.setError('加载文档失败');
        console.error('加载文档失败:', error);
      } finally {
        this.setLoading(false);
      }
    },
    
    /**
     * 添加分类
     * @param name 分类名称
     * @param parentId 父分类ID
     */
    async addCategory(name: string, parentId: string = '') {
      try {
        this.setLoading(true);
        await createDocCategory(name, parentId || '0');
        message.success('分类添加成功');
        await this.loadCategories();
        return true;
      } catch (error) {
        this.setError('添加分类失败');
        message.error('添加分类失败');
        return false;
      } finally {
        this.setLoading(false);
      }
    },
    
    /**
     * 更新分类
     * @param categoryId 分类ID
     * @param name 新分类名称
     */
    async updateCategory(categoryId: string, name: string) {
      try {
        this.setLoading(true);
        await updateDocCategory(categoryId, name);
        message.success('分类修改成功');
        await this.loadCategories();
        return true;
      } catch (error) {
        this.setError('修改分类失败');
        message.error('修改分类失败');
        return false;
      } finally {
        this.setLoading(false);
      }
    },
    
    /**
     * 删除分类
     * @param categoryId 分类ID
     */
    async removeCategory(categoryId: string) {
      try {
        this.setLoading(true);
        await deleteDocCategory(categoryId);
        message.success('删除成功');
        
        // 如果删除的是当前选中的分类，则清空当前选中
        if (this.currentCategory === categoryId) {
          this.currentCategory = 'all';
        }
        
        await this.loadCategories();
        return true;
      } catch (error) {
        this.setError('删除分类失败');
        message.error('删除失败');
        return false;
      } finally {
        this.setLoading(false);
      }
    },
    
    /**
     * 删除文档
     * @param docBizId 文档ID
     */
    async removeDocument(docBizId: string) {
      try {
        const success = await deleteDocument(docBizId);
        if (success) {
          message.success('删除成功');
          this.loadDocuments();
          return true;
        } else {
          message.error('删除失败');
          return false;
        }
      } catch (error) {
        message.error('删除失败');
        return false;
      }
    },
    
    /**
     * 生成文档问答
     * @param docBizId 文档ID
     */
    async generateQA(docBizId: string) {
      try {
        const success = await generateDocQA(docBizId);
        if (success) {
          message.success('已开始生成问答，请稍后刷新查看');
          this.loadDocuments();
          return true;
        } else {
          message.error('生成问答失败');
          return false;
        }
      } catch (error) {
        message.error('操作失败');
        return false;
      }
    },
    
    // 获取分类列表
    async fetchCategories() {
      this.setLoading(true);
      const timestamp = parseInt(String(new Date().getTime() / 1000))
      try {
        const response = await request<{
          code: number;
          message: string;
          data: Category[];
        }>('https://lke.tencentcloudapi.com', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Host': 'lke.tencentcloudapi.com',
            'X-TC-Action': 'ListDocCate',
            'X-TC-Timestamp': timestamp,
            'X-TC-Version': '2023-11-30',
            'X-TC-Region': 'ap-guangzhou',
            'X-TC-Language': 'zh-CN',
            'X-TC-Token': 'd9mMOOFj742EazUzxUprp2QxZH8GrJQa9784036296586bab357b0302ac3384fcdN-M7SAoazn8v8j1ji6FE7mjkLU1_dOcwy-z8izKXmEoircS6jRGbeHF6b-2tuJwWqYy_taWznn4TqSbKinR2izJw55ZbmRXUk3d7caKxonSjjxYUNVeTA9VB3s0prweVvzlz-6Y6zuYKFUVFRhc-QEpv7SOOVK8ljGqRmWLkeWd4Ioq7MAO-RpO5_wZSxNGSbNWckT9curN52cnHgNd0wmMIea3qp93t6GbtXsM0WcIvEZtQSWzmT99HffziYvvmRdCU81pNbRMvJUPmjC1KQ',
            'Authorization': 'TC3-HMAC-SHA256 Credential=AKIDrPL6WPX5Y2E8lZ6O_rPFaxUrizx0Lcc7Tm7EEOVY_zy8m1bCMDy4cUqU0AdaEfbd/2025-04-27/lke/tc3_request, SignedHeaders=content-type;host, Signature=b0474666853d85a40d823d0d467e257abaaf34acf2826f3bbb83d5dc780f4f58'
          },
          data: {
            BotBizId: import.meta.env.VITE_BOTBIZID || '1902651563333648384',
          }
        });
        
        this.categories = response.data;
      } catch (error) {
        console.error('获取知识库分类失败:', error);
        this.setError('获取知识库分类失败');
        throw error;
      } finally {
        this.setLoading(false);
      }
    },
    
    // 获取文档列表
    async fetchDocuments(params = {}) {
      this.setLoading(true);
      
      try {
        const response = await request<{
          code: number;
          message: string;
          data: PaginatedResult<Document>;
        }>('/tencent/v1', {
          method: 'POST',
          headers: {
            'X-TC-Action': 'ListDoc'
          },
          params: {
            pageSize: this.pageSize,
            pageNumber: this.pageNumber,
            query: this.searchQuery || undefined,
            ...params
          },
          data: {
            BotBizId: import.meta.env.VITE_BOTBIZID || '1902651563333648384',
            Action: 'ListDocCate',
            Version: '2023-08-08',
            Region: 'ap-guangzhou'
          }
        });
        
        this.documents = response.data.list;
        this.total = String(response.data.total);
      } catch (error) {
        console.error('获取知识库文档失败:', error);
        this.setError('获取知识库文档失败');
        throw error;
      } finally {
        this.setLoading(false);
      }
    },
    
    // 上传文档
    async uploadDocuments(files: any[], category?: string) {
      this.setLoading(true);
      
      try {
        const formData = new FormData();
        files.forEach(file => {
          formData.append('files', file.originFileObj);
        });
        
        if (category && category !== 'all') {
          formData.append('category', category);
        }
        
        const response = await request<{
          code: number;
          message: string;
          data: { success: number; fail: number; };
        }>('', {
          method: 'POST',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        // 重新获取文档列表
        await this.fetchDocuments();
        
        return response.data;
      } catch (error) {
        console.error('上传文档失败:', error);
        this.setError('上传文档失败');
        throw error;
      } finally {
        this.setLoading(false);
      }
    },
    
    // 删除文档
    async deleteDocument(docId: string) {
      this.setLoading(true);
      
      try {
        const response = await request<{
          code: number;
          message: string;
          data: null;
        }>(`/api/knowledge/documents/${docId}`, {
          method: 'DELETE'
        });
        
        // 从状态中移除该文档
        this.documents = this.documents.filter(doc => doc.docBizId !== docId);
        
        return response;
      } catch (error) {
        console.error('删除文档失败:', error);
        this.setError('删除文档失败');
        throw error;
      } finally {
        this.setLoading(false);
      }
    },
    
    // 搜索文档
    async searchDocuments(query: string) {
      this.searchQuery = query;
      this.pageNumber = 1; // 重置页码
      await this.fetchDocuments();
    },
    
    // 分页变化
    async onPaginationChange(page: number, pageSize: number) {
      this.pageNumber = page;
      this.pageSize = pageSize;
      await this.fetchDocuments();
    }
  },
}); 